<?php
/**
 * Created by zengxianfen on 2020/7/17 17:12.
 */

namespace App\Exception\Handler;


use App\Exception\ServiceException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ServiceExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        if ($throwable instanceof ServiceException){
            $data = json_encode(['state'=>0,'msg'=>$throwable->getMessage()],JSON_UNESCAPED_UNICODE);
            $this->stopPropagation();
            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }
        return $response;
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }

}